package com.binance.sysconf.mq;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.support.converter.AbstractJsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConversionException;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * Description: MQ消息2Json转换器.
 *  (由于发送方没严格将消息转换成json格式,故此转换器没强制要求输出json)
 * @author hongchaoMao - Date 2018/7/23
 */
public class Obj2JsonMessageConverter extends AbstractJsonMessageConverter {

    private static Log log = LogFactory.getLog(Obj2JsonMessageConverter.class);

    private ObjectMapper objectMapper = new ObjectMapper();

    {
        // 发送对象日期转换
        objectMapper.writer(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }

    @Override
    protected Message createMessage(Object object, MessageProperties messageProperties) {
        byte[] bytes;
        try {
            String jsonString = objectMapper.writeValueAsString(object);
            bytes = jsonString.getBytes(getDefaultCharset());
        }
        catch (IOException e) {
            throw new MessageConversionException(
                    "Failed to convert Message content", e);
        }
        messageProperties.setContentType(MessageProperties.CONTENT_TYPE_JSON);
        messageProperties.setContentEncoding(getDefaultCharset());
        messageProperties.setContentLength(bytes.length);

        return new Message(bytes, messageProperties);
    }

    @Override
    public Object fromMessage(Message message) throws MessageConversionException {
        Object content = null;
        MessageProperties properties = message.getMessageProperties();
        if (properties != null) {
            String contentType = properties.getContentType();
            String encoding = properties.getContentEncoding();
            if (encoding == null) {
                encoding = getDefaultCharset();
            }
            if (contentType == null || !contentType.contains("json")) {
                // 针对非json的message,暂且也用String来进行处理
                log.warn("Could not convert incoming message with content-type ["
                        + contentType + "], 'json' keyword missing.");
            }
            try {
                content = new String(message.getBody(), encoding);
            }
            catch (IOException e) {
                throw new MessageConversionException(
                        "Failed to convert Message content", e);
            }
        }
        return content;
    }
}
